<template>
  <div class="aftersales-approval-page">
    <el-card>
      <template #header>
        <div class="page-header">
          <h3>售后审批</h3>
        </div>
      </template>

      <!-- 审批统计 -->
      <div class="approval-stats">
        <el-row :gutter="16">
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-value">{{ stats.pending }}</div>
              <div class="stat-label">待审批</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-value">{{ stats.approved }}</div>
              <div class="stat-label">已通过</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-value">{{ stats.rejected }}</div>
              <div class="stat-label">已拒绝</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-value">{{ stats.today }}</div>
              <div class="stat-label">今日待审</div>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :model="searchForm" inline>
          <el-form-item label="售后单号">
            <el-input v-model="searchForm.afterSalesNo" placeholder="请输入售后单号" clearable />
          </el-form-item>
          <el-form-item label="售后类型">
            <el-select v-model="searchForm.type" placeholder="请选择类型" clearable>
              <el-option label="退货退款" value="退货退款" />
              <el-option label="仅退款" value="仅退款" />
              <el-option label="换货" value="换货" />
              <el-option label="维修" value="维修" />
            </el-select>
          </el-form-item>
          <el-form-item label="审批状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
              <el-option label="待审批" value="待审批" />
              <el-option label="已通过" value="已通过" />
              <el-option label="已拒绝" value="已拒绝" />
            </el-select>
          </el-form-item>
          <el-form-item label="紧急程度">
            <el-select v-model="searchForm.urgent" placeholder="请选择" clearable>
              <el-option label="普通" value="普通" />
              <el-option label="紧急" value="紧急" />
              <el-option label="特急" value="特急" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 标签页 -->
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <el-tab-pane label="待我审批" name="pending">
          <el-table :data="tableData" v-loading="loading" stripe>
            <el-table-column type="selection" width="55" />
            <el-table-column prop="afterSalesNo" label="售后单号" width="150" />
            <el-table-column prop="orderNo" label="原订单号" width="150" />
            <el-table-column prop="type" label="售后类型" width="100">
              <template #default="{ row }">
                <el-tag :type="getTypeTagType(row.type)">
                  {{ row.type }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="customerName" label="客户" width="120" />
            <el-table-column prop="refundAmount" label="退款金额" width="120">
              <template #default="{ row }">
                <span v-if="row.refundAmount">¥{{ row.refundAmount.toFixed(2) }}</span>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column prop="reason" label="售后原因" width="150" show-overflow-tooltip />
            <el-table-column prop="urgent" label="紧急程度" width="100">
              <template #default="{ row }">
                <el-tag v-if="row.urgent === '特急'" type="danger">特急</el-tag>
                <el-tag v-else-if="row.urgent === '紧急'" type="warning">紧急</el-tag>
                <el-tag v-else type="info">普通</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="applyTime" label="申请时间" width="180" />
            <el-table-column label="等待时长" width="100">
              <template #default="{ row }">
                <span :class="{'warning-text': getWaitHours(row.applyTime) > 24}">
                  {{ getWaitHours(row.applyTime) }}小时
                </span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row }">
                <el-button type="primary" size="small" @click="handleApprove(row)">
                  审批
                </el-button>
                <el-button type="info" size="small" @click="handleView(row)">
                  查看
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="我已审批" name="approved">
          <el-table :data="approvedData" v-loading="loading" stripe>
            <el-table-column prop="afterSalesNo" label="售后单号" width="150" />
            <el-table-column prop="orderNo" label="原订单号" width="150" />
            <el-table-column prop="type" label="售后类型" width="100">
              <template #default="{ row }">
                <el-tag :type="getTypeTagType(row.type)">
                  {{ row.type }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="customerName" label="客户" width="120" />
            <el-table-column prop="refundAmount" label="退款金额" width="120">
              <template #default="{ row }">
                <span v-if="row.refundAmount">¥{{ row.refundAmount.toFixed(2) }}</span>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column prop="approveStatus" label="审批结果" width="100">
              <template #default="{ row }">
                <el-tag v-if="row.approveStatus === '已通过'" type="success">通过</el-tag>
                <el-tag v-else-if="row.approveStatus === '已拒绝'" type="danger">拒绝</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="approveRemark" label="审批意见" show-overflow-tooltip />
            <el-table-column prop="approveTime" label="审批时间" width="180" />
            <el-table-column label="操作" width="120" fixed="right">
              <template #default="{ row }">
                <el-button type="info" size="small" @click="handleView(row)">
                  查看
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="全部" name="all">
          <el-table :data="allData" v-loading="loading" stripe>
            <el-table-column prop="afterSalesNo" label="售后单号" width="150" />
            <el-table-column prop="orderNo" label="原订单号" width="150" />
            <el-table-column prop="type" label="售后类型" width="100">
              <template #default="{ row }">
                <el-tag :type="getTypeTagType(row.type)">
                  {{ row.type }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="customerName" label="客户" width="120" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.status)">
                  {{ row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="approver" label="审批人" width="100" />
            <el-table-column prop="applyTime" label="申请时间" width="180" />
            <el-table-column label="操作" width="120" fixed="right">
              <template #default="{ row }">
                <el-button type="info" size="small" @click="handleView(row)">
                  查看
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 审批对话框 -->
    <el-dialog v-model="approveVisible" title="售后审批" width="800px">
      <div v-if="currentRow" class="approve-content">
        <!-- 基本信息 -->
        <el-descriptions :column="2" border>
          <el-descriptions-item label="售后单号">{{ currentRow.afterSalesNo }}</el-descriptions-item>
          <el-descriptions-item label="原订单号">{{ currentRow.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="售后类型">
            <el-tag :type="getTypeTagType(currentRow.type)">{{ currentRow.type }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="客户">{{ currentRow.customerName }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ currentRow.phone }}</el-descriptions-item>
          <el-descriptions-item label="申请时间">{{ currentRow.applyTime }}</el-descriptions-item>
          <el-descriptions-item label="售后原因" :span="2">
            {{ currentRow.reason }}
          </el-descriptions-item>
          <el-descriptions-item label="问题描述" :span="2">
            {{ currentRow.description || '-' }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 商品明细 -->
        <el-divider content-position="left">商品明细</el-divider>
        <el-table :data="currentRow.items" border size="small">
          <el-table-column prop="productName" label="商品名称" />
          <el-table-column prop="specification" label="规格" width="120" />
          <el-table-column prop="quantity" label="数量" width="80" />
          <el-table-column prop="unitPrice" label="单价" width="100">
            <template #default="{ row }">
              ¥{{ row.unitPrice.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column label="小计" width="120">
            <template #default="{ row }">
              ¥{{ (row.unitPrice * row.quantity).toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>

        <!-- 退款信息 -->
        <el-divider content-position="left">退款信息</el-divider>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="退款金额">
            <span class="amount-text">¥{{ currentRow.refundAmount?.toFixed(2) }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="退款方式">
            {{ currentRow.refundMethod || '-' }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 审批表单 -->
        <el-divider content-position="left">审批意见</el-divider>
        <el-form :model="approveForm" label-width="100px">
          <el-form-item label="审批结果" required>
            <el-radio-group v-model="approveForm.result">
              <el-radio label="通过">审核通过</el-radio>
              <el-radio label="拒绝">审核拒绝</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="退款金额" v-if="approveForm.result === '通过'">
            <el-input-number 
              v-model="approveForm.refundAmount" 
              :precision="2" 
              :min="0"
              :max="currentRow.refundAmount"
            />
            <span class="tip-text">（最大金额：¥{{ currentRow.refundAmount?.toFixed(2) }}）</span>
          </el-form-item>
          <el-form-item label="审批意见" required>
            <el-input 
              v-model="approveForm.remark" 
              type="textarea" 
              :rows="4"
              placeholder="请输入审批意见..."
            />
          </el-form-item>
          <el-form-item label="加急处理" v-if="approveForm.result === '通过'">
            <el-switch v-model="approveForm.urgent" />
            <span class="tip-text">（加急处理将优先安排退款）</span>
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <el-button @click="approveVisible = false">取消</el-button>
        <el-button type="primary" @click="submitApprove">提交审批</el-button>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailVisible" title="售后单详情" width="900px">
      <div class="detail-content" v-if="currentRow">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="售后单号">{{ currentRow.afterSalesNo }}</el-descriptions-item>
          <el-descriptions-item label="原订单号">{{ currentRow.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="售后类型">
            <el-tag :type="getTypeTagType(currentRow.type)">{{ currentRow.type }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(currentRow.status)">{{ currentRow.status }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="客户">{{ currentRow.customerName }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ currentRow.phone }}</el-descriptions-item>
          <el-descriptions-item label="申请时间">{{ currentRow.applyTime }}</el-descriptions-item>
          <el-descriptions-item label="审批时间">{{ currentRow.approveTime || '-' }}</el-descriptions-item>
          <el-descriptions-item label="审批人">{{ currentRow.approver || '-' }}</el-descriptions-item>
          <el-descriptions-item label="审批意见" :span="2">
            {{ currentRow.approveRemark || '-' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'

// 统计数据
const stats = reactive({
  pending: 15,
  approved: 23,
  rejected: 8,
  today: 6
})

// 搜索表单
const searchForm = reactive({
  afterSalesNo: '',
  type: '',
  status: '',
  urgent: ''
})

// 标签页
const activeTab = ref('pending')

// 表格数据
const tableData = ref([])
const approvedData = ref([])
const allData = ref([])
const loading = ref(false)

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 审批对话框
const approveVisible = ref(false)
const detailVisible = ref(false)
const currentRow = ref(null)

const approveForm = reactive({
  result: '通过',
  refundAmount: 0,
  remark: '',
  urgent: false
})

// 获取售后类型标签类型
const getTypeTagType = (type) => {
  const typeMap = {
    '退货退款': 'danger',
    '仅退款': 'warning',
    '换货': 'primary',
    '维修': 'info'
  }
  return typeMap[type] || ''
}

// 获取状态标签类型
const getStatusType = (status) => {
  const statusMap = {
    '待审批': 'warning',
    '已通过': 'success',
    '已拒绝': 'danger',
    '待退货': 'info',
    '已完成': 'success'
  }
  return statusMap[status] || ''
}

// 计算等待时长
const getWaitHours = (applyTime) => {
  const now = new Date()
  const apply = new Date(applyTime)
  const hours = Math.floor((now - apply) / (1000 * 60 * 60))
  return hours
}

// 加载数据
const loadData = () => {
  loading.value = true
  
  setTimeout(() => {
    if (activeTab.value === 'pending') {
      tableData.value = [
        {
          id: 1,
          afterSalesNo: 'AS202501190001',
          orderNo: 'SO202501150234',
          type: '退货退款',
          customerName: '张三',
          refundAmount: 6999.00,
          reason: '质量问题',
          urgent: '紧急',
          applyTime: '2025-01-19 10:30:00',
          phone: '13800138000',
          refundMethod: '原路退回',
          description: '手机屏幕有划痕',
          items: [
            {
              productName: '华为 Mate 60 Pro 12GB+512GB',
              specification: '曜金黑',
              quantity: 1,
              unitPrice: 6999.00
            }
          ]
        },
        {
          id: 2,
          afterSalesNo: 'AS202501190002',
          orderNo: 'SO202501160145',
          type: '换货',
          customerName: '李四',
          refundAmount: 0,
          reason: '商品破损',
          urgent: '特急',
          applyTime: '2025-01-18 09:15:00',
          phone: '13900139000',
          description: '包装破损，要求换货',
          items: [
            {
              productName: '小米14 Ultra 16GB+1TB',
              specification: '钛金属',
              quantity: 1,
              unitPrice: 6499.00
            }
          ]
        }
      ]
      pagination.total = 15
    } else if (activeTab.value === 'approved') {
      approvedData.value = [
        {
          id: 3,
          afterSalesNo: 'AS202501180003',
          orderNo: 'SO202501140089',
          type: '仅退款',
          customerName: '王五',
          refundAmount: 9999.00,
          approveStatus: '已通过',
          approveRemark: '同意退款',
          approveTime: '2025-01-18 15:00:00'
        }
      ]
      pagination.total = 23
    } else {
      allData.value = [
        ...tableData.value,
        ...approvedData.value
      ]
      pagination.total = 46
    }
    
    loading.value = false
  }, 500)
}

// 标签页切换
const handleTabChange = (tab) => {
  pagination.page = 1
  loadData()
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  loadData()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    afterSalesNo: '',
    type: '',
    status: '',
    urgent: ''
  })
  handleSearch()
}

// 分页改变
const handlePageChange = (page) => {
  pagination.page = page
  loadData()
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.page = 1
  loadData()
}

// 审批
const handleApprove = (row) => {
  currentRow.value = row
  approveForm.result = '通过'
  approveForm.refundAmount = row.refundAmount
  approveForm.remark = ''
  approveForm.urgent = false
  approveVisible.value = true
}

// 提交审批
const submitApprove = () => {
  if (!approveForm.remark) {
    ElMessage.warning('请输入审批意见')
    return
  }
  
  ElMessage.success('审批提交成功')
  approveVisible.value = false
  loadData()
}

// 查看详情
const handleView = (row) => {
  currentRow.value = row
  detailVisible.value = true
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.aftersales-approval-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h3 {
  margin: 0;
  color: #303133;
}

.approval-stats {
  margin-bottom: 20px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
}

.stat-item {
  text-align: center;
  color: white;
}

.stat-value {
  font-size: 32px;
  font-weight: bold;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  opacity: 0.9;
}

.search-area {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.warning-text {
  color: #f56c6c;
  font-weight: bold;
}

.approve-content {
  max-height: 600px;
  overflow-y: auto;
}

.amount-text {
  font-size: 18px;
  font-weight: bold;
  color: #f56c6c;
}

.tip-text {
  margin-left: 10px;
  color: #909399;
  font-size: 12px;
}

.detail-content {
  max-height: 500px;
  overflow-y: auto;
}
</style>

